package com.example.recite_words.activity;

import static com.example.recite_words.util.UriUtils.getFileType;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.example.recite_words.Bean.User;
import com.example.recite_words.MainActivity;
import com.example.recite_words.R;
import com.example.recite_words.util.Config;
import com.example.recite_words.util.RWfile;
import com.example.recite_words.util.Send_data;
import com.example.recite_words.util.UriUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;

import de.hdodenhof.circleimageview.CircleImageView;

public class Setting extends MainActivity {
    private CircleImageView user_image;
    private ActivityResultLauncher<Intent> resultLauncher;
    private JSONObject jsonObject;
    private void toServer(File file,String FileType) throws IOException {
        FileReader fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(fileReader);
        StringBuilder sb = new StringBuilder();
        String temp = "";
        while ((temp = br.readLine()) != null) {
            // 拼接换行符
            sb.append(temp + "\n");
        }
        br.close();
        String js = sb.toString();
        String data = "Email=" + URLEncoder.encode(MainActivity.TheUser.getId(),"UTF-8")
                + "&File=" + URLEncoder.encode(js,"UTF-8") +
                "&FileType=" + URLEncoder.encode(FileType,"UTF-8");
        new Thread(() -> {
            jsonObject = Send_data.do_post(Setting.this,data,Config.UPLOAD_FLIE);
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        Button log_out = findViewById(R.id.set_logout);
        Button checkout = findViewById(R.id.set_checkout);
        log_out.setOnClickListener(new BtnClickListener());
        checkout.setOnClickListener(new BtnClickListener());
        TextView username = findViewById(R.id.set_name);
        ImageView back = findViewById(R.id.set_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent main_intent = new Intent();
                main_intent.setClass(Setting.this, Main.class);
                startActivity(main_intent);
            }
        });
        //MainActivity.TheUser = new User("370932447@qq.com","xx");
        username.setText(MainActivity.TheUser.getNickName());
         resultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        // 判断手机系统版本号
                        if (result.getResultCode() == RESULT_OK) {

                            Uri uri = result.getData().getData();

                            user_image.setImageURI(uri);
                            //TODO文件格式

                            String source = UriUtils.getFileAbsolutePath(Setting.this,uri);

                            String FileType = getFileType(source);
                            String path =  UriUtils.getFilePathFromURI(Setting.this,uri,"user_icon." + FileType);
                            MainActivity.TheUser.setIcon(path);
                            //MainActivity.TheUser.setIcon(path + "/user_icon." + FileType);
                            try {
                                MainActivity.TheUser.WriteUser(Setting.this);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            RWfile.deleteFile(source);
                            //MainActivity.TheUser.setIcon(path);
                            File file = new File(path);
                                try {
                                    toServer(file,FileType);
                                    if(jsonObject == null){

                                    }
                                    else {
                                        switch ((int)jsonObject.get("code")){
                                            case 200:
                                                break;
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            /*String imagePath = getImagePath(uri,null);
                            displayImage(imagePath);*/
                        }
                        else{

                        }
                    }
                });
        user_image = findViewById(R.id.myavatar);

        Uri uri = MainActivity.TheUser.IconToUri();
        if(uri != null){
            user_image.setImageURI(uri);
        }
        else {
            user_image.setImageResource(R.drawable.user_icon);
        }
        user_image.setOnClickListener(new ChangeImage());

    }

    class ChangeImage implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            if (ContextCompat.checkSelfPermission(Setting.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    !=
                    PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(Setting.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

            } else {
                // 调用系统相册
                openAlbum();
                //user_image.setImageURI(Uri.fromFile(new File(MainActivity.TheUser.getIcon())));
            }
        }



        private void openAlbum() {
            // 使用Intent来跳转
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            // setType是设置类型，只要系统中满足该类型的应用都会被调用，这里需要的是图片
            intent.setType("image/*");

            // 打开满足条件的程序，CHOOSE_PHOTO是一个常量，用于后续进行判断，下面会说
            resultLauncher.launch(intent);
        }


    }

    class BtnClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            //MainActivity.TheUser = new User("370932447@qq.com","xx");
            new Thread(() -> {
                jsonObject = Send_data.do_post(Setting.this, "Email=" + MainActivity.TheUser.getId(), Config.LOGOUT_URL);
                switch ((int)jsonObject.get("code")){
                    case Config.logout_success:{
                        Toast.makeText(getApplicationContext(), "退出成功！", Toast.LENGTH_SHORT).show();
                        MainActivity.TheUser = new User(MainActivity.TheUser.getId(),MainActivity.TheUser.getNickName());
                        try {
                            MainActivity.TheUser.WriteUser(Setting.this);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Intent login_intent = new Intent();
                        login_intent.setClass(Setting.this, Login.class);
                        startActivity(login_intent);
                        break;
                    }
                    case Config.link_error:{
                        Toast.makeText(getApplicationContext(), "网络连接错误！", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case Config.io_error: {
                        Toast.makeText(getApplicationContext(), "返回文件读取错误！", Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }).start();
        }
    }
}
